package net.mujiwulian.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import net.mujiwulian.entity.Acupoint;
import net.mujiwulian.entity.AcupointType;
import net.mujiwulian.service.AcupointDetailsService;
import net.mujiwulian.service.AcupointService;
import net.mujiwulian.service.AcupointTypeService;
import net.mujiwulian.view.AcupointDetails;
import net.mujiwulian.view.UserSimple;
import net.mujiwulian.vo.PageQuery;
import net.mujiwulian.vo.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Author: silence
 * @Description:
 * @Date:Create：in 2019/12/28 19:04
 */
@Slf4j
@RestController
@RequestMapping("/acupoint")
public class AcupointController {

    @Value("${file-path}")
    private String filePath;

    private final AcupointService acupointService;
    private final AcupointDetailsService acupointDetailsService;
    private final AcupointTypeService acupointTypeService;

    public AcupointController(AcupointService acupointService, AcupointDetailsService acupointDetailsService, AcupointTypeService acupointTypeService) {
        this.acupointService = acupointService;
        this.acupointDetailsService = acupointDetailsService;
        this.acupointTypeService = acupointTypeService;
    }

    /**
     * ----------------------------------------------穴位分类---------------------------------------------------
     */

    @GetMapping("/type/select")
    public Result<List<AcupointType>> selectType(boolean b) {
        LambdaQueryWrapper<AcupointType> lq = Wrappers.lambdaQuery();
        if (b) {
            lq.select(AcupointType::getId, AcupointType::getName);
        }
        return new Result<>(Result.CodeStatus.OK, "获取穴位分类信息", acupointTypeService.list(lq));
    }

    @PostMapping("/type/delete")
    @Transactional(rollbackFor = {Exception.class})
    public Result<Void> deleteType(@RequestBody AcupointType acupointType) {
        return new Result<>("删除穴位分类", acupointTypeService.removeById(acupointType.getId()));
    }

    @PostMapping("/type/insertOrUpdate")
    public Result<Void> insertOrUpdateType(UserSimple userSimple, @RequestBody AcupointType acupointType) {
        if (StringUtils.isEmpty(acupointType.getName())) {
            return new Result<>(Result.CodeStatus.FAIL, "参数错误");
        }
        if (acupointType.getId() == null && acupointTypeService.getOne(new QueryWrapper<AcupointType>().eq("name", acupointType.getName())) != null) {
            return new Result<>(Result.CodeStatus.FAIL, "名字已存在");
        }
        acupointType.setUpdateTime(LocalDateTime.now());
        acupointType.setOperator(userSimple.getUsername());
        return new Result<>("操作", acupointTypeService.saveOrUpdate(acupointType));
    }


    /**
     * ----------------------------------------------穴位---------------------------------------------------
     */

    @PostMapping("/select")
    public Result<IPage<AcupointDetails>> select(@RequestBody PageQuery<AcupointDetails> pageQuery) {
        AcupointDetails acupointDetails = pageQuery.getT() == null ? new AcupointDetails() : pageQuery.getT();
        LambdaQueryWrapper<AcupointDetails> lq = Wrappers.lambdaQuery();
        lq.like(StringUtils.isNotEmpty(acupointDetails.getTypeName()), AcupointDetails::getTypeName, acupointDetails.getTypeName());
        lq.like(StringUtils.isNotEmpty(acupointDetails.getName()), AcupointDetails::getName, acupointDetails.getName());
        return new Result<>(Result.CodeStatus.OK, "获取穴位信息", acupointDetailsService.page(pageQuery.getPageCondition(), lq));
    }

    @GetMapping("/selectSimple")
    public Result<List<Acupoint>> select() {
        return new Result<>(Result.CodeStatus.OK, "获取穴位简单信息", acupointService.list(new QueryWrapper<Acupoint>().select("id", "name")));
    }

    @PostMapping("/insertOrUpdate")
    public Result<Void> insertOrUpdate(Acupoint acupoint) {
        Acupoint at = null;
        if (acupoint.getId() != null) {
            at = acupointService.getById(acupoint.getId());
        } else {
            if (acupointService.getOne(new QueryWrapper<Acupoint>().eq("name", acupoint.getName())) != null) {
                return new Result<>(Result.CodeStatus.FAIL, "名字已存在");
            }
            acupoint.setCreateTime(LocalDateTime.now());
        }
        try {
            if (acupoint.getImg() != null) {
                String path = "/files/acupoint/" + UUID.randomUUID().toString() + acupoint.getImg().getOriginalFilename();
                FileUtils.copyInputStreamToFile(acupoint.getImg().getInputStream(), new File(this.filePath + path));
                acupoint.setImgUrl(path);
                if (at != null) {
                    File deleteFile = new File(this.filePath + at.getImgUrl());
                    log.warn("删除文件:" + at.getImgUrl() + "-----" + deleteFile.delete());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result<>(Result.CodeStatus.FAIL, "网络异常");
        }
        return new Result<>("操作", acupointService.saveOrUpdate(acupoint));
    }

    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody List<Integer> ids) {
        List<Acupoint> list = acupointService.list(new QueryWrapper<Acupoint>().in("id", ids).select("img_url"));
        list.forEach(acupoint -> log.warn("删除文件:" + acupoint.getImgUrl() + "-----" + new File(this.filePath + acupoint.getImgUrl()).delete()));
        return new Result<>("删除穴位", acupointService.removeByIds(ids));
    }

}
